import DyForm from "../DyForm";
import {ElementType} from "../using/typing/field-config";

export type AddEleEventHandler = (e: AddEleEvent) => void

export interface AddEleEvent {
    type: ElementType
}

export class FormDesign {
    public static readonly ADD_ELE = 'add-ele-event'

    private readonly _el: HTMLDivElement
    private addEleHandler: AddEleEventHandler[] = []

    constructor(private form: DyForm) {
        this._el = document.createElement('div');
        this._el.style.width = `calc( ( 100vw - ${this.form.getConfig().width}px ) / 2 )`
        this._el.style.overflow = 'auto'
        this.addButtons()
    }

    public getEl() {
        return this._el
    }

    public addEleEventListener(handler: AddEleEventHandler) {
        if (this.addEleHandler.indexOf(handler) < 0) {
            this.addEleHandler.push(handler)
        }
    }

    private addButtons() {

        const addClass = (ele: HTMLElement) => {
            ele.classList.add('w-24', 'h-8', 'subpixel-antialiased', 'bg-sky-600', 'rounded-lg', 'border-indigo-300', 'outline-1', 'outline-cyan-500', 'shadow-blue-500/50', 'text-slate-300', 'm-1')
        }

        const addEventListener = (ele: HTMLElement, type: ElementType) => {
            ele.addEventListener('click', () => {
                if (this.addEleHandler && this.addEleHandler.length) {
                    this.addEleHandler.forEach(handler => {
                        try{
                            handler({type})
                        } catch (e){
                            console.error(e)
                        }
                    })
                }
            })
        }
        const input = document.createElement('button');
        input.innerText = 'Input';
        addClass(input)
        addEventListener(input, ElementType.INPUT)
        this._el.appendChild(input)

        const select = document.createElement('button');
        select.innerText = 'Select';
        addClass(select)
        addEventListener(select, ElementType.SELECT)
        this._el.appendChild(select)
    }
}
